<template>
  <div class="back-top" v-if="showBackTop" @click="goBackTop">
    <van-icon name="back-top" />
  </div>
</template>
<script>
import { ref } from '@vue/reactivity'
export default {
  setup () {
    const showBackTop = ref(false)
    document.addEventListener('scroll', () => {
      if (window.pageYOffset >= 500) {
        showBackTop.value = true
      } else {
        showBackTop.value = false
      }
    })
    const goBackTop = () => {
      const time = setInterval(() => {
        const scrollTop = Math.floor((0 - window.pageYOffset) / 15)
        if (window.pageYOffset === 0) {
          clearInterval(time)
        }
        window.scroll(0, window.pageYOffset + scrollTop)
      }, 15)
    }
    return {
      showBackTop,
      goBackTop
    }
  }
}
</script>
<style scoped>
.back-top {
  position: fixed;
  right: 20px;
  bottom: 150px;
  color: red;
  font-size: 30px;
  z-index: 2;
}
</style>
